package com.cadre.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cadre.common.utils.SecurityUtils;
import com.cadre.common.utils.annotation.SysLog;
import com.cadre.common.utils.common.GenerateUUID;
import com.cadre.common.utils.common.HttpContextUtils;
import com.cadre.common.utils.common.IPUtils;
import com.cadre.common.utils.oldutil.*;
import com.cadre.system.domain.officer.*;
import com.cadre.system.mapper.A01Mapper;
import com.cadre.system.mapper.A19Mapper;
import com.cadre.system.mapper.A79Mapper;
import com.cadre.system.service.A79Service;
import com.cadre.system.service.DPersontagService;
import com.cadre.system.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service("A79Service")
public class A79ServiceImpl extends ServiceImpl<A79Mapper, A79> implements A79Service {
    private static final String xls = "xls";
    private static final String xlsx = "xlsx";
    @Autowired
    A79Mapper a79Mapper;
    @Autowired
    A01Mapper a01Mapper;
    @Autowired
    private A19Mapper a19Mapper;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    DPersontagService dPeronTagService;

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<A79> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.orderByAsc(A79::getSerial);
        return new PageUtils(this.baseMapper.selectPage(new Query(params).getPage(),lambdaQueryWrapper));
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public List<A79> selectList(String personId) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        LambdaQueryWrapper<A79> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(A79::getPersonid, personId);
        lambdaQueryWrapper.orderByAsc(A79::getSerial);
        List<A79> list = a79Mapper.selectList(lambdaQueryWrapper);
        for (A79 a79 : list) {
            if (a79.getA7923() == null) {
                try {
                    a79.setAgeString(String.valueOf(AgeUtil.getAgeFromBirthTime(simpleDateFormat.format(a79.getA7922()))));
                } catch (Exception e) {
                    a79.setAgeString("");
                }
            } else if (String.valueOf(a79.getA7923()).contains("去世") || String.valueOf(a79.getA7923()).contains("已故") || String.valueOf(a79.getA7923()).contains("死亡")) {
                a79.setAgeString("");
            } else {
                try {
                    a79.setAgeString(String.valueOf(AgeUtil.getAgeFromBirthTime(simpleDateFormat.format(a79.getA7922()))));
                } catch (Exception e2) {
                    a79.setAgeString("");
                }
            }
        }
        return list;
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    @Transactional(rollbackFor = {Exception.class})
    public int updateByPrimaryKeySelective(A79 a79) {
        return this.baseMapper.updateByPrimaryKeySelective(a79);
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    @Transactional
    public int insertBatchSimple(List<A79> a79List) {
        return this.a79Mapper.insertBatchSimple(a79List);
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public String readExcelContentByList(MultipartFile file, String personId) {
        new ArrayList();
        List<A79> a79List = new ArrayList<>();
        try {
            String msg = checkFile(file);
            if (msg != "") {
                return msg;
            }
            List<Map<Integer, String>> list = ExcelImpotUtils.readExcel(file);
            if (list.size() <= 0) {
                return "空Excel!";
            }
            if (list.size() <= 3) {
                return "Excel内容与模板不符";
            }
            String name = list.get(1).get(1);
            A01 a = (A01) this.a01Mapper.selectById(personId);
            if (a == null) {
                return "请填写正确的人员id";
            }
            if (name == null) {
                return "请在Excel填写正确的姓名";
            }
            if (!a.getA0101().toString().equals(name)) {
                return "在Excel填写的姓名要与导入Excel中姓名相同";
            }
            for (int i = 3; i < list.size(); i++) {
                Map<Integer, String> map = list.get(i);
                A79 a1 = new A79();
                A79 a2 = new A79();
                a1.setFlowid(GenerateUUID.getUUID());
                a1.setA7910(map.get(1));
                a1.setA7921(map.get(2));
                a1.setA7922(getData(map.get(3)));
                a1.setA7914(map.get(4));
                a1.setA7923(map.get(5));
                a1.setPersonid(personId);
                if (i == 3 || i == 4 || i == 5) {
                    a1.setIsout((short) 1);
                }
                a2.setFlowid(GenerateUUID.getUUID());
                a2.setA7910(map.get(7));
                a2.setA7921(map.get(8));
                a2.setA7922(getData(map.get(9)));
                a2.setA7914(map.get(10));
                a2.setA7923(map.get(11));
                a2.setPersonid(personId);
                if (i == 3 || i == 7 || i == 11) {
                    a2.setIsout((short) 1);
                }
                a79List.add(a1);
                a79List.add(a2);
            }
            List<A79> a79List2 = new ArrayList<>();
            for (int n = 0; n < a79List.size(); n++) {
                if (a79List.get(n).getA7910() != null && a79List.get(n).getA7921() != null && !a79List.get(n).getA7921().equals("") && !a79List.get(n).getA7910().equals("")) {
                    a79List2.add(a79List.get(n));
                }
            }
            if (a79List2.size() > 0) {
                LambdaQueryWrapper<A79> lambdaQueryWrapper = new LambdaQueryWrapper();
                lambdaQueryWrapper.eq(A79::getPersonid, personId);
                this.a79Mapper.delete(lambdaQueryWrapper);
                for (int m = 0; m < a79List2.size(); m++) {
                    this.a79Mapper.insert(a79List2.get(m));
                }
                this.dPeronTagService.updateA79Tag(personId);
            }
            return "操作成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "操作成功";
        }
    }

    private Date getData(String string) {
        if (string == null || string.equals("") || !isDate(string)) {
            return null;
        }
        return DateUtil.stringtoDate(string, "yyyyMM");
    }

    public boolean isDate(String date) {
        if (date != null) {
            return Pattern.compile(new StringBuffer("[12]\\d{3}-?(0[1-9]|1[0-2])").toString()).matcher(date).matches();
        }
        return false;
    }

    private String checkFile(MultipartFile file) throws IOException {
        if (null == file) {
            return "文件不存在！";
        }
        String fileName = file.getOriginalFilename();
        if (fileName.endsWith(xls) || fileName.endsWith(xlsx)) {
            return "";
        }
        return fileName + "不是excel文件";
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    @Transactional(rollbackFor = {Exception.class})
    public int deleteByPersonId(String personid) {
        recordLog(personid);
        this.a79Mapper.deleteA79AByPersonidA(personid);
        return this.a79Mapper.deleteByPersonId(personid);
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    @SysLog(value = "删除干部家庭成员信息", target = "A01", set = "A79", type = DateUtil.SUB_MONTH)
    public int deleteByFlowid(String[] flowid) {
        return this.a79Mapper.deleteBatchIds(Arrays.asList(flowid));
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    @Transactional(rollbackFor = {Exception.class})
    @SysLog(value = "新增干部家庭成员信息", target = "A01", set = "A79", type = 0)
    public int insertForlog(A79 entity) {
        getQinshu(entity);
        return this.a79Mapper.insert(entity);
    }

    @Override
    public void updateA79A(A19 a19) {
        String personid = a19.getPersonid();
        Short a1945 = a19.getA1945();
        if (a1945 != null && a1945.shortValue() == 1) {
            List<A79> a79List = this.a79Mapper.selectByPersonid(personid);
            if (a79List.size() > 0) {
                for (A79 a79 : a79List) {
                    getQinshu(a79);
                }
            }
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public void deleteA79AByPersonidA(String personid) {
        this.a79Mapper.deleteA79AByPersonidA(personid);
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public List<Chart> getA79AWarning() {
        return this.a79Mapper.getA79AWarning();
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public List<A01> inverseQueryAvoid() {
        return this.a01Mapper.inverseQueryAvoid();
    }

    @Override // com.tdqy.cadre.modular.profess.service.A79Service
    public List<Map<String, Object>> selectA79AByPerAndTeam(String personid, String a1915) {
        return this.a79Mapper.selectA79AByPerAndTeam(personid, a1915);
    }

    public void getQinshu(A79 a79) {
        Object name = a79.getA7921();
        Object birth = DateUtil.dateToString(a79.getA7922(), "yyyy-MM");
        Object sfz = a79.getA7913();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("A0101", name);
        map2.put("birth", birth);
        map2.put("A0107", sfz);
        A01 a01 = this.a01Mapper.selectByNameAndBirth(map2);
        if (a01 != null) {
            List<A19> a19List = this.a19Mapper.selectIsBanziByPerson(a79.getPersonid());
            if (a19List.size() > 0) {
                boolean isTrue = false;
                List<String> teamIdList = new ArrayList<>();
                for (A19 a19 : a19List) {
                    String a1915 = a19.getA1915();
                    LambdaQueryWrapper<A19> lambdaQueryWrapper = new LambdaQueryWrapper();
                    lambdaQueryWrapper.eq(A19::getA1915, a1915);
                    lambdaQueryWrapper.eq(A19::getPersonid, a01.getFlowid());
                    lambdaQueryWrapper.eq(A19::getA1945, 1);
                    lambdaQueryWrapper.eq(A19::getA1935, 1);
                    if (this.a19Mapper.selectMaps(lambdaQueryWrapper).size() > 0) {
                        isTrue = true;
                        teamIdList.add(a1915);
                    }
                }
                List<String> teamIdList2 = (List) teamIdList.stream().distinct().collect(Collectors.toList());
                if (isTrue) {
                    for (String teamId : teamIdList2) {
                        this.a79Mapper.insertA79A(new A79A(a79.getPersonid(), a01.getFlowid(), a79.getA7910(), teamId));
                    }
                }
            }
        }
    }

    private void recordLog(String personid) {
        LambdaQueryWrapper<A79> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(A79::getPersonid, personid);
        List<A79> lists = this.baseMapper.selectList(lambdaQueryWrapper);
        if (lists.size() != 0) {
            String oldParam = JSON.toJSONString(lists);
            SysLogEntity sysLog = new SysLogEntity();
            sysLog.setOldparams(oldParam);
            doSaveLog(sysLog, personid);
        }
    }

    private void doSaveLog(SysLogEntity sysLog, String targetid) {
        sysLog.setOperation("删除干部家庭成员信息");
        sysLog.setOperationtable("A79");
        sysLog.setOperationset("A79");
        sysLog.setOperationtype(2);
        sysLog.setTargetid(targetid);
        sysLog.setParams(targetid);
        sysLog.setIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));
        sysLog.setUsername(SecurityUtils.getLoginUser().getUsername());
        sysLog.setTime(5L);
        sysLog.setCreateDate(new Date());
        this.sysLogService.save(sysLog);
    }
}
